package com.zbkj.crmeb.store.service.impl;

import javax.annotation.Resource;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.constants.Constants;
import com.github.pagehelper.PageInfo;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.request.MerchantListRequest;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.chant.vo.ChannelMerchantVO;
import com.zbkj.crmeb.enums.SwitchEnum;
import com.zbkj.crmeb.store.model.SupplierDiscount;
import com.zbkj.crmeb.store.request.AddDiscountRequest;
import com.zbkj.crmeb.store.request.AddSupplierRequest;
import com.zbkj.crmeb.system.model.MessageConfig;
import com.zbkj.crmeb.system.model.SystemConfig;
import com.zbkj.crmeb.system.service.SystemConfigService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.crmeb.store.dao.SupplierDao;
import com.zbkj.crmeb.store.model.Supplier;
import com.zbkj.crmeb.store.service.SupplierService;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author Mr.Zhang
 * @Description CategoryServiceImpl 接口实现
 * @since 2020-04-16
 */
@Slf4j
@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierDao, Supplier> implements SupplierService {

    @Resource
    private SupplierDao supplierDao;

    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private SystemConfigService systemConfigService;

    /**
     * 获取供应商名称
     *
     * @param suppliersId
     * @return
     */
    @Override
    public String getSuppliersName(String suppliersId) {
        String suppliersName = "";
        if (StringUtils.isNotBlank(suppliersId)) {
            Supplier supplier = supplierDao.selectById(suppliersId);
            if (ObjectUtils.isNotEmpty(supplier)) {
                suppliersName = supplier.getSuppliersName();
            }
        }
        return suppliersName;
    }

    @Override
    public Supplier getSupplierBarcode(Integer merId) {
        LambdaQueryWrapper<Supplier> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Supplier::getMerId, merId);
        Supplier supplier = supplierDao.selectOne(wrapper);

        return supplier;
    }

    @Override
    public List<Supplier> getVisibleSupplier(Integer merId) {
        ChannelMerchant channelMerchant = Optional.ofNullable(channelMerchantService.getChannelMerchantByMerId(merId)).orElse(new ChannelMerchant());
        List<Integer> suppliersIdList = Optional.ofNullable(JSON.parseArray(channelMerchant.getSuppliersIds(), Integer.class)).orElse(new ArrayList<>());
        if (CollectionUtils.isEmpty(suppliersIdList)) {
            List<ChannelMerchant> list = channelMerchantService.list(Wrappers.<ChannelMerchant>lambdaQuery().eq(ChannelMerchant::getChannelType, 3).eq(ChannelMerchant::getIsDel, 0));
            List<String> collect = list.stream().map(ChannelMerchant::getSuppliersIds).collect(Collectors.toList());
            collect.forEach(e -> suppliersIdList.add(Integer.valueOf(e.replace("[", "").replace("]", ""))));
        }
        List<Supplier> list = this.list(Wrappers.<Supplier>lambdaQuery()
                        .eq(Supplier::getIsDeleted, false)
                        .in(CollectionUtils.isNotEmpty(suppliersIdList), Supplier::getId, suppliersIdList)
                //.isNull(Supplier :: getMerId)
        );
        SystemConfig systemConfig = systemConfigService.getOne(Wrappers.<SystemConfig>lambdaQuery()
                        .eq(SystemConfig::getName, Constants.CONFIG_KEY_SHOW_SUPPLIER + "_" + merId)
                        .last("limit 1")
//                .eq(SystemConfig::getFormId,merId)
        );
        if (Objects.equals(systemConfig.getValue(), "1")) {
            return list;
        } else if (Objects.equals(systemConfig.getValue(), "0")) {
            return new ArrayList<>();
        } else {
            List<Integer> showSuppliersIdList = Optional.ofNullable(JSON.parseArray(channelMerchant.getShowSuppliersIds(), Integer.class)).orElse(new ArrayList<>());
            if(CollUtil.isEmpty(showSuppliersIdList)) return list;
            return list.stream().filter(e -> showSuppliersIdList.contains(e.getId())).collect(Collectors.toList());
           /* List<ChannelMerchant> channelMerchantList = channelMerchantService.list(Wrappers.<ChannelMerchant>lambdaQuery().eq(ChannelMerchant::getChannelType,3).eq(ChannelMerchant::getIsDel, 0));
            if(CollectionUtils.isEmpty(channelMerchantList)){
                return new ArrayList<>();
            }
            List<Integer> integerList = new ArrayList<>();
            channelMerchantList.stream().forEach(channelMerchant1 -> {
                String suppliersIds = channelMerchant1.getSuppliersIds().replace("[","").replace("]","");
                if (Objects.equals(channelMerchant1.getChannelName(),channelMerchant.getChannelName())){
                    integerList.addAll(Convert.toList(Integer.class,suppliersIds.split(",")));
                }
                if (StringUtils.isNotBlank(channelMerchant1.getRateIds())){
                    List<Integer> ids = Convert.toList(Integer.class,channelMerchant1.getRateIds().split(","));
                    if (ids.contains(merId)){
                        integerList.addAll(Convert.toList(Integer.class,suppliersIds.split(",")));
                    }
                }
            });
            return list.stream().filter(e -> integerList.contains(e.getId())).collect(Collectors.toList());*/
        }
    }


    /**
     * 创建
     * @param request
     * @return
     */
    @Override
    public boolean addSupplier(AddSupplierRequest request) {

        Supplier supplier = new Supplier();
        BeanUtil.copyProperties(request,supplier,"id");
        supplier.setCreateTime(new Date())
                .setEditTime(new Date());

        supplier.setIsDeleted("0");

        LambdaQueryWrapper<Supplier> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 设置查询条件
        lambdaQueryWrapper.select(Supplier::getIsEurope)
                .orderByDesc(Supplier::getIsEurope)
                .last("LIMIT 1");
        List<Supplier> entityList = supplierDao.selectList(lambdaQueryWrapper);
        if(!CollectionUtils.isEmpty(entityList)) {
            supplier.setIsEurope(entityList.get(0).getIsEurope() + 1);
        }


        return this.save(supplier);
    }

}

